package com.uinnova.product.eam.service.todo;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uinnova.product.eam.service.todo.dto.GTDeletePendingJobInfo;
import com.uinnova.product.eam.service.todo.dto.GTFinishPendingJobInfo;
import com.uinnova.product.eam.service.todo.dto.GTSendPendingJobInfo;
import com.uinnova.project.base.diagram.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class GTJobSvcImpl implements GTJobSvc {
    /**
     * 待办服务地址
     */
    @Value("${pendingJob.serverUrl:https://bpm-uat.axzq.com.cn}")
    private String pendingJobServer;

//    @Value("${pendingJob.oauth2Url}")
//    private String oauth2Url;


    @Value("${pendingJob.appName:AXEA}")
    private String appName;

    @Value("${pendingJob.moudleName:AXEA_modlue}")
    private String moudleName;

    @Value("${pendingJob.entityId:dk12d22suiql6}")
    private String entityId;

    @Value("${pendingJob.entityName:todo}")
    private String entityName;

    @Value("${pendingJob.entityKey:EA待办}")
    private String entityKey;

    @Value("${pendingJob.AppKey:ticCLw5l2SYoCCAR}")
    private String appKey;

    @Value("${pendingJob.AppSecret:4a74806b3e0c8a52da32f875dea034d76123c303}")
    private String appSecret;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 发送待办接口
     */
    final  String sendUrl = "/openapi/sys-notifybus/sysNotifyComponent/send";
    /**
     * 置为已办接口
     */
    final  String finishUrl = "/openapi/sys-notifybus/sysNotifyComponent/done";
    /**
     * 删除待办接口
     */
    final  String deleteTodoUrl = "/openapi/sys-notifybus/sysNotifyComponent/removeTodo";
    /**
     * 删除已办接口
     */
    final  String deleteDoneUrl = "/openapi/sys-notifybus/sysNotifyComponent/removeDone";
    /**
     * 获取token接口
     */
    final  String getTokenUrl = "/authapi/getToken";



    /**
     * 发送待办方法
     * @param sendPendingJobInfo
     * @return 返回待办id
     */
    public Boolean sendPendingJob(GTSendPendingJobInfo sendPendingJobInfo){
        try{
            String token = this.getToken();
            HttpRequest request = new HttpRequest(pendingJobServer + sendUrl + "?access_token=" + token);
            request.setMethod(Method.POST);

            sendPendingJobInfo.setConfig(appName,moudleName,entityId,entityName,entityKey);
            request.body(JSONUtil.toJsonStr(sendPendingJobInfo));
            HttpResponse response = request.execute();
            if(response.isOk()) {
                /**
                 * todo：解析数据，success为true成功，若成功则返回data字段的值
                 */
                String responseBody = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                Boolean success =  jsonObject.getBool("success");
                return success;
            }
            log.error("待办接口返回-{}",response.body());
            throw new RuntimeException("发送待办失败");
        }catch (Exception e){
            log.error("发送待办异常-{}",e);
            e.printStackTrace();
            throw new RuntimeException("发送待办异常");
        }

    }

    /**
     * 置为已办
     * @param finishPendingJobInfo
     * @return
     */
    public Boolean finishPendingJob (GTFinishPendingJobInfo finishPendingJobInfo){
        try{
            String token = this.getToken();
            HttpRequest request = new HttpRequest(pendingJobServer + finishUrl + "?access_token=" + token);
            request.setMethod(Method.POST);
            finishPendingJobInfo.setConfig(appName,moudleName,entityId,entityName,entityKey);
            request.body(JSONUtil.toJsonStr(finishPendingJobInfo));
            HttpResponse response = request.execute();
            if(response.isOk()) {
                /**
                 * todo：解析数据，success为true成功，若成功则返回data字段的值
                 */
                String responseBody = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                Boolean success =  jsonObject.getBool("success");
                if(!success){
                    log.info("已办接口返回-{}",response.body());
                }
               return  success;
            }
            log.info("已办接口返回-{}",response.body());
            throw new RuntimeException("发送已办失败");
        }catch (Exception e){
            log.info("发送已办异常-{}",e);
            e.printStackTrace();
            throw new RuntimeException("发送已办异常");
        }
    }


    /**
     * 删除待办
     * @param deletePendingJobInfo
     * @return
     */
    public Boolean deleteTodoJob (GTDeletePendingJobInfo deletePendingJobInfo){
        try{
            String token = this.getToken();
            HttpRequest request = new HttpRequest(pendingJobServer + deleteTodoUrl + "?access_token=" + token);
            request.setMethod(Method.POST);
            deletePendingJobInfo.setConfig(appName,moudleName,entityId,entityName,entityKey);
            request.body(JSONUtil.toJsonStr(deletePendingJobInfo));
            HttpResponse response = request.execute();
            if(response.isOk()) {
                /**
                 * todo：解析数据，success为true成功，若成功则返回data字段的值
                 */
                String responseBody = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                Boolean success =  jsonObject.getBool("success");
                if(!success){
                    log.error("已办接口返回-{}",response.body());
                }
                return success;
            }
            throw new RuntimeException("发送已办失败");
        }catch (Exception e){
            log.error("发送已办异常-{}",e);
            e.printStackTrace();
            throw new RuntimeException("发送已办异常");
        }
    }

    /**
     * 删除已办
     * @param deletePendingJobInfo
     * @return
     */
    public Boolean deleteDoneJob (GTDeletePendingJobInfo deletePendingJobInfo){
        try{
            String token = this.getToken();
            HttpRequest request = new HttpRequest(pendingJobServer + deleteDoneUrl + "?access_token=" + token);
            request.setMethod(Method.POST);
            deletePendingJobInfo.setConfig(appName,moudleName,entityId,entityName,entityKey);
            request.body(JSONUtil.toJsonStr(deletePendingJobInfo));
            HttpResponse response = request.execute();
            if(response.isOk()) {
                /**
                 * todo：解析数据，success为true成功，若成功则返回data字段的值
                 */
                String responseBody = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                Boolean success =  jsonObject.getBool("success");
                if(!success){
                    log.info("已办接口返回-{}",response.body());
                }
                return  success;
            }
            log.error("删除接口返回-{}",response.body());
            throw new RuntimeException("删除已办失败");
        }catch (Exception e){
            log.error("发送已办异常-{}",e);
            e.printStackTrace();
            throw new RuntimeException("发送已办异常");
        }
    }


    /**
     * 获取token
     * @return
     */
    private String getToken(){
        String accessToken = null;
        if(redisUtil.hasKey("pendingJobToken")){
            return (String) redisUtil.get("pendingJobToken");
        }
        try{
            HttpRequest request = new HttpRequest(pendingJobServer + getTokenUrl);
            request.setMethod(Method.POST);
            JSONObject body = new JSONObject();

            body.set("appKey",appKey);
            body.set("appSecret",appSecret);

            request.body(body.toString());
            HttpResponse response = request.execute();
            if(response.isOk()) {
                /**
                 * todo：解析数据，access_token存在且有值为超管，若成功则返回access_token字段的值
                 */
                String responseBody = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                String token =  jsonObject.getStr("access_token");
                int expert =  jsonObject.getInt("expires_in");
                if( token != null ){
                    redisUtil.set("pendingJobToken",token,expert - 500);
                    return  token;
                }
            }
            log.error("获取待办token接口返回-{}",response.body());
            throw new RuntimeException("获取待办接口token失败");
        }catch (Exception e){
            log.info("获取待办接口token异常-{}",e);
            e.printStackTrace();
            throw new RuntimeException("获取待办接口token异常");
        }
    }
}
